#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>//大小端转换、字符串16位短整型32位长整形之间的转换、字符串和网络类型之间的转换
#include <string>
#include <iostream>
#include <cstring>
#include <functional>
#include "InitAddr.hpp"

const int defaultfd = -1;
using func_t = std::function<void(int, const std::string&, InitAddr&)>;

class udpServer{
public:
    udpServer(uint16_t port, func_t func)
        : _sockfd(defaultfd)
        , _port(port)
        , _isrunning(false)
        , _func(func)
    {}

    void Init() //创建套接字-填充sockaddr_in结构体-绑定
    {
        //          网络套接（表示采用ipv4）   用数据报套接字   协议类型
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0); 
        if(_sockfd < 0)
        {
            std::cerr << "socket fail" << std::endl;
            return;
        }
        std::cout << "the sockfd is:" << _sockfd << std::endl;

        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;

        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        int n = bind(_sockfd, (struct sockaddr*)&local, sizeof(local));
        if(n < 0)
        {
            std::cout << "绑定失败" << std::endl;
            exit(1);
        }
        std::cout << "绑定成功" << std::endl;
        // //查看绑定netstat -anup
    }

    void Start() //收发消息
    {
        _isrunning = true;
        while(_isrunning)
        {
            char buffer[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t s = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&peer, &len);
            if(s < 0)
            {
                std::cout << "revcfrom fail" << std::endl;
                exit(1);
            }

            InitAddr client(peer);
            buffer[s] = 0;//今天收到的内容认为是英语单词
            _func(_sockfd, buffer, client);
        }
    }

    ~udpServer(){

    }
private:
    int _sockfd;
    uint16_t _port;//网络协议的两字节的端口号
    //std::string _ip;//字符串风格的点分十进制
    bool _isrunning;

    func_t _func; //服务器的回调函数，用来对数据进行处理
};